// src/stores/auth.js
import { defineStore } from 'pinia'
// import router from '@/router'; // 如果需要在登出后跳转，稍后引入

export const useAuthStore = defineStore('auth', {
  state: () => ({
    // 从本地存储初始化用户信息和 Token
    user: JSON.parse(localStorage.getItem('user')) || null,
    token: localStorage.getItem('accessToken') || null,
    // 根据 Token 是否存在判断登录状态
    isLoggedIn: !!localStorage.getItem('accessToken'),
  }),

  getters: {
    // 计算属性：是否已认证
    isAuthenticated: (state) => state.isLoggedIn,
    // 计算属性：获取当前用户信息
    currentUser: (state) => state.user,
  },

  actions: {
    // 设置认证信息 (登录成功后调用)
    setAuth({ user, token }) {
      this.user = user
      this.token = token
      this.isLoggedIn = true
      console.log('Setting auth in store:', { user, token })
      // 将信息保存到本地存储
      localStorage.setItem('user', JSON.stringify(user))
      localStorage.setItem('accessToken', token)
      // 可以在这里设置 axios 默认 header (可选，因为拦截器已经处理了)
      // import apiClient from '@/services/api';
      // apiClient.defaults.headers.common['Authorization'] = `Bearer ${token}`;
    },

    // 清除认证信息 (登出时调用)
    logout() {
      this.user = null
      this.token = null
      this.isLoggedIn = false
      // 从本地存储移除信息
      localStorage.removeItem('user')
      localStorage.removeItem('accessToken')
      // 删除 axios 默认 header (可选)
      // import apiClient from '@/services/api';
      // delete apiClient.defaults.headers.common['Authorization'];
      // TODO: 跳转到登录页
      // router.push('/login');
    },
  },
})
